package com.sky.controller.admin;

import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Setmeal;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("adminSetmealController")
@Slf4j
@RequestMapping("/admin/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @CacheEvict(cacheNames = "categorySetmealCache",key = "#setmeal.categoryId")
    @PostMapping
    public Result addSetmeal(@RequestBody SetmealDTO setmeal) {
        log.info("addSetmeal: {}", setmeal);
        setmealService.saveWithDish(setmeal);
        return Result.success();
    }

    //todo: 这个接口的返回值，SetmealVO没有写入categoryName，接口设计似乎不合理？？？
    @GetMapping("/{id}")
    public Result<SetmealVO> getSetmealById(@PathVariable Long id) {
        log.info("getSetmealById: {}", id);
        SetmealVO setmealVO=setmealService.getSetmealWithDishesById(id);
        return Result.success(setmealVO);
    }

    //todo: categoryName和setName的差别，为什么要存在category
    // 一个category是一类套餐，一个套餐有多个菜品
    @GetMapping("/page")
    public Result<PageResult> pageQuerySetmeal(SetmealPageQueryDTO query) {
        log.info("pageQuerySetmeal: {}", query);
        PageResult setmeals=setmealService.pageQuery(query);
        return Result.success(setmeals);
    }

    //由于没有放回categoryId，所以全部删除
    @CacheEvict(cacheNames = "categorySetmealCache",allEntries = true)
    @PostMapping("/status/{status}")
    public Result startOrStop(@PathVariable Integer status,Long id) {
        log.info("startOrStop, id: {}, status: {}", id,status);
        setmealService.startOrStop(status,id);
        return Result.success();
    }

    //删除套餐，也要把套餐的菜品明细删除
    @CacheEvict(cacheNames = "categorySetmealCache",allEntries = true)
    @DeleteMapping
    public Result deleteSetmealWithDishByIds(@RequestParam List<Long> ids) {
        log.info("deleteSetmeals: {}", ids);
        setmealService.deleteSetmealWithDishByIds(ids);
        return Result.success();
    }

    @PutMapping
    //categorySetmealCache所有都删除，是因为这个套餐可能改到其他的category，会影响两份数据
    @CacheEvict(cacheNames = {"categorySetmealCache","setmealDishItem"},allEntries = true)
    public Result update(@RequestBody SetmealDTO setmealDTO) {
        setmealService.update(setmealDTO);
        return Result.success();
    }





}
